<template>
  <va-modal v-model="isVisible" hide-default-actions title="导入表情包">
    <div class="import-container">
      <va-alert v-if="!isAuthenticated" color="warning" icon="warning">
        请先登录后再导入表情包
      </va-alert>
      
      <template v-else>
        <va-alert v-if="message.text" :color="message.type" icon="info">
          {{ message.text }}
        </va-alert>
        
        <div class="import-instructions">
          <h4>图片导入说明</h4>
          <p>将表情包图片放入后端服务器的 <code>uploads/import</code> 目录中，然后点击下方的导入按钮开始导入。</p>
          <p>导入时系统会自动进行 AI 分析，为每张图片生成相关标签。</p>
        </div>
        
        <form @submit.prevent="handleImport" class="import-form">
          <va-input
            v-model="dateFolder"
            label="目标日期 (可选)"
            class="mb-4"
            placeholder="YYYYMMDD 格式，例如: 20240401"
            :error="!!dateError"
            :error-messages="dateError"
            @update:modelValue="dateError = ''"
          />
          
          <va-checkbox
            v-model="analyzeImages"
            class="mb-4"
            label="使用 AI 分析生成图片标签"
          />
          
          <div class="actions">
            <va-button type="submit" color="primary" :loading="isLoading">
              开始导入
            </va-button>
            <va-button @click="closeDialog" flat>
              取消
            </va-button>
          </div>
        </form>
        
        <div v-if="importResults" class="results-container">
          <h4>导入结果</h4>
          <div class="results-stats">
            <div class="stat-item">
              <div class="stat-value">{{ importResults.imported }}</div>
              <div class="stat-label">成功导入</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ importResults.analyzed || 0 }}</div>
              <div class="stat-label">AI 分析</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ importResults.total }}</div>
              <div class="stat-label">总文件数</div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </va-modal>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useAuth } from '../composables/useAuth'
import { importFiles, syncTags } from '../api/uploads'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'import-success'])

const { isAuthenticated } = useAuth()

const isVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const dateFolder = ref('')
const analyzeImages = ref(true)
const isLoading = ref(false)
const dateError = ref('')
const message = ref({ text: '', type: 'info' })
const importResults = ref(null)
const isSyncingTags = ref(false)

watch(() => props.modelValue, (newVal) => {
  // Reset form when dialog opens
  if (newVal) {
    resetForm()
  }
})

const validateDate = (date) => {
  if (!date) return true // 日期是可选的
  
  // 检查格式是否为 YYYYMMDD
  if (!/^\d{8}$/.test(date)) {
    return false
  }
  
  // 验证是否为有效日期
  const year = parseInt(date.substring(0, 4))
  const month = parseInt(date.substring(4, 6)) - 1 // JS 月份从 0 开始
  const day = parseInt(date.substring(6, 8))
  
  const dateObj = new Date(year, month, day)
  return (
    dateObj.getFullYear() === year &&
    dateObj.getMonth() === month &&
    dateObj.getDate() === day
  )
}

/**
 * 同步标签数据到标签表
 */
const syncTagsData = async () => {
  if (isSyncingTags.value) return
  
  isSyncingTags.value = true
  
  try {
    await syncTags()
    // 刷新或更新消息
    message.value = { 
      text: message.value.text + ' (标签数据已同步)', 
      type: message.value.type 
    }
  } catch (error) {
    // 同步失败不影响主流程，只记录错误
    console.error('标签同步失败:', error)
  } finally {
    isSyncingTags.value = false
  }
}

const handleImport = async () => {
  // 验证日期格式
  if (dateFolder.value && !validateDate(dateFolder.value)) {
    dateError.value = '请输入有效的日期格式 (YYYYMMDD)'
    return
  }
  
  isLoading.value = true
  message.value = { text: '', type: 'info' }
  importResults.value = null
  
  try {
    const response = await importFiles({
      date: dateFolder.value || undefined,
      analyze_images: analyzeImages.value
    })
    
    importResults.value = response.data.results
    message.value = { text: response.data.message, type: 'success' }
    
    // 导入成功后同步标签数据
    await syncTagsData()
    
    // 延迟关闭对话框
    setTimeout(() => {
      emit('import-success', response.data)
    }, 3000)
  } catch (error) {
    const errorMsg = error.response?.data?.error || '导入失败，请检查后端服务'
    message.value = { text: errorMsg, type: 'danger' }
  } finally {
    isLoading.value = false
  }
}

const resetForm = () => {
  dateFolder.value = ''
  analyzeImages.value = true
  dateError.value = ''
  message.value = { text: '', type: 'info' }
  importResults.value = null
}

const closeDialog = () => {
  isVisible.value = false
}
</script>

<style scoped>
.import-container {
  padding: 1rem 0;
}

.mb-4 {
  margin-bottom: 1rem;
}

.actions {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
}

.import-instructions {
  background-color: var(--border-color);
  padding: 1rem;
  border-radius: 0.5rem;
  margin-bottom: 1.5rem;
}

.import-instructions code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0.2rem 0.4rem;
  border-radius: 0.25rem;
  font-family: monospace;
}

.results-container {
  margin-top: 2rem;
  border-top: 1px solid var(--border-color);
  padding-top: 1.5rem;
}

.results-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 1rem;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  color: var(--primary-color);
}

.stat-label {
  font-size: 0.875rem;
  color: var(--text-secondary);
}
</style> 